package com.nian.common.lock.redis;

import com.nian.redis.cache.JedisClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.params.SetParams;

/**
 * 用途：
 * 开发：zhangmj
 * 日期：2020/4/13 0013 16:48
 */
@Slf4j
@Service
public class RedisDistributedUpgradeLock implements IRedisLock {

    @Autowired
    JedisClient jedisClient;

    @Override
    public boolean lock(String lockName, String requestId) {
        return lock(lockName, requestId, IRedisLock.TIMEOUT);
    }

    @Override
    public boolean lock(String lockName, String requestId, int millisecondsToExpire) {
        String result = jedisClient.set(lockName, requestId, SetParams.setParams().nx().px(millisecondsToExpire));
        if (LOCK_SUCCESS.equals(result)) {
            log.info("获取锁 Thread Name: {} ,requestId: {}", Thread.currentThread().getName(), requestId);
            return true;
        }
        return false;
    }

    @Override
    public boolean unLock(String lockName, String requestId) {
        if (jedisClient.get(lockName).equals(requestId)) {
            log.info("释放锁 Thread Name: {} ,requestId: {}", Thread.currentThread().getName(), requestId);
            jedisClient.remove(lockName);
            return true;
        }
        return false;
    }
}
